package com.ruoyi.file.utils;

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author william.zhao
 * @version 1.0
 * @date 2024/06/18/ 15:44
 * @since jdk-17.0.2
 */
public class CscpTxtToPDFUtils {
    private static final Logger log = LoggerFactory.getLogger(CscpTxtToPDFUtils.class);

    public static String covertTxtToPDF(String txtPath, String pdfPath) {
        try {
            // 使用UTF-8编码读取TXT文件
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(txtPath), StandardCharsets.UTF_8));
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(pdfPath));
            Document document = new Document(pdfDoc, PageSize.A4);

            // 加载支持中文的字体，并使用Identity-H编码（如果字体支持）
            // PdfFont font = PdfFontFactory.createFont("C:\\Windows\\Fonts\\STSONG.TTF", "Identity-H");
            String fontPath = "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc";
            PdfFont font = PdfFontFactory.createFont(fontPath, "UniGB-UCS2-H");

            String line;
            while ((line = reader.readLine()) != null) {
                Paragraph p = new Paragraph(line).setFont(font); // 设置字体
                document.add(p);
            }

            document.close(); // 关闭文档，确保所有内容都被写入PDF
        } catch (IOException e) {
            e.printStackTrace();
            return null; // 返回null或适当的错误消息
        }
        return pdfPath;
    }
}
